package chat

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
)

func NewChat() *Chat {
	return &Chat{
		url:    "https://api.openai.com/v1/chat/completions",
		apiKey: "",
	}
}

type Chat struct {
	url    string
	apiKey string
}

func (r *Chat) Url(url string) *Chat {
	r.url = url

	return r
}
func (r *Chat) ApiKey(apiKey string) *Chat {
	r.apiKey = apiKey

	return r
}

func (r *Chat) Stream(f StreamCallbackFn) error {
	payload := map[string]interface{}{
		"model": "qwen-turbo",
		"messages": []map[string]string{
			{"role": "user", "content": "Hello, how are you?"},
		},
		"stream": true,
	}

	body, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", r.url, bytes.NewBuffer(body))
	if err != nil {
		return err
	}

	req.Header.Set("Authorization", "Bearer "+r.apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return errors.New(fmt.Sprintf("Error: received non-OK HTTP status %s\n", resp.Status))
	}

	reader := bufio.NewReader(resp.Body)
	for {
		line, err := reader.ReadBytes('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		if len(line) > 0 {
			err := f(string(line))
			if err != nil {
				return err
			}
		}
	}

	return nil
}
